package com.bird.ecmainmenu3.presenter;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.SurfaceTexture;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;

import androidx.annotation.NonNull;

import com.bird.ecmainmenu3.R;
import com.bird.ecmainmenu3.base.OnMainUiListener;
import com.bird.ecmainmenu3.model.AppInfo;
import com.bird.ecmainmenu3.util.Utils;

import java.io.IOException;
import java.util.Objects;

public class MainPresenter implements MediaPlayer.OnPreparedListener {
    private static final String TAG = Utils.TAG + MainPresenter.class.getSimpleName();

    private OnMainUiListener mMainUiCallback;
    private MediaPlayer mMediaPlayer;
    private final Context mContext;

    private final BroadcastReceiver mDateTimeReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d(TAG, "mDateTimeReceiver: " + intent);
            if (Objects.equals(intent.getAction(), Intent.ACTION_TIME_TICK)
                    || Objects.equals(intent.getAction(), Intent.ACTION_TIME_CHANGED)
                    || Objects.equals(intent.getAction(), Intent.ACTION_TIMEZONE_CHANGED)) {
                if (mMainUiCallback!= null) {
                    mMainUiCallback.onDateTimeChanged();
                    Log.d(TAG, "onDateTimeChanged: ");
                }
            }
        }
    };

    private final BroadcastReceiver mAppStateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d(TAG, "mAppStateReceiver: " + intent);
            if (Objects.equals(intent.getAction(), Intent.ACTION_PACKAGE_ADDED)
                    || Objects.equals(intent.getAction(), Intent.ACTION_PACKAGE_REMOVED)
                    || Objects.equals(intent.getAction(), Intent.ACTION_PACKAGE_REPLACED)) {
                String action = intent.getAction();
                if (action != null) {
                    Uri uri = intent.getData();
                    if (uri != null) {
                        String packageName = uri.getSchemeSpecificPart();
                        PackageManager pm = context.getPackageManager();
                        switch (action) {
                            case Intent.ACTION_PACKAGE_ADDED:
                                Log.d(TAG, "App installed: " + packageName);
                                try {
                                    Drawable icon = pm.getApplicationInfo(packageName, 0).loadIcon(pm);
                                    String label = pm.getApplicationInfo(packageName, 0).loadLabel(pm).toString();
                                    String cls = Objects.requireNonNull(Objects.requireNonNull(pm.getLaunchIntentForPackage(packageName)).getComponent()).getClassName();
                                    AppsManager.getInstance().notifyAppAdded(new AppInfo(icon, label, packageName, cls));
                                    Utils.saveAppData(mContext, "pkg_" + packageName, packageName);
                                    Utils.saveAppData(mContext, "cls_" + packageName, cls);
                                } catch (PackageManager.NameNotFoundException e) {
                                    Log.e(TAG, "App installed: " + packageName + ", but not found in PackageManager");
                                }
                                break;

                            case Intent.ACTION_PACKAGE_REMOVED:
                                Log.d(TAG, "App uninstalled: " + packageName);
                                AppsManager.getInstance().notifyAppRemoved(packageName);
                                Utils.removeAppData(mContext, "pkg_" + packageName);
                                Utils.removeAppData(mContext, "cls_" + packageName);
                                break;

                            case Intent.ACTION_PACKAGE_REPLACED:
                                Log.d(TAG, "App updated: " + packageName);
                                break;
                        }
                    }
                }
            }
        }
    };

    public MainPresenter(Context context) {
        mContext = context;
        registerListener();
    }

    public void setCallback(OnMainUiListener callback) {
        mMainUiCallback = callback;
    }

    private void registerDateTimeListener() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_TIME_TICK);
        filter.addAction(Intent.ACTION_TIME_CHANGED);
        filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
        mContext.registerReceiver(mDateTimeReceiver, filter);
    }

    private void registerAppStateListener() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_PACKAGE_ADDED);
        filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
        filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
        filter.addDataScheme("package");
        mContext.registerReceiver(mAppStateReceiver, filter);
    }

    private void unRegisterAppStateListener() {
        mContext.unregisterReceiver(mAppStateReceiver);
    }


    private void registerListener() {
        registerDateTimeListener();
        registerAppStateListener();
    }

    private void unRegisterListener() {
        unRegisterDateTimeListener();
        unRegisterAppStateListener();
    }

    private void unRegisterDateTimeListener() {
        mContext.unregisterReceiver(mDateTimeReceiver);
    }

    public void destroy() {
        releaseMediaPlayer();
        unRegisterListener();
    }

    public void startApp(String pkg, String cls) {
        Log.d(TAG, "srtApp: pkg=" + pkg + ", cls=" + cls);
        Utils.startApp(mContext, pkg, cls);
    }

    public void createMediaPlayer(@NonNull SurfaceTexture surfaceTexture) {
        if (mMediaPlayer == null) {
            mMediaPlayer = new MediaPlayer();

            try {
                Uri uri = Uri.parse("android.resource://" + mContext.getPackageName() + "/" + R.raw.v_avatar);
                Log.d(TAG, "createMediaPlayer: uri=" + uri.toString());
                mMediaPlayer.setDataSource(mContext, uri);
            } catch (IOException e) {
                Log.e(TAG, "createMediaPlayer: ", e);
            }

            mMediaPlayer.setSurface(new Surface(surfaceTexture));
            mMediaPlayer.setLooping(true);

            mMediaPlayer.setOnPreparedListener(mp -> {
                if (!mMediaPlayer.isPlaying()) {
                    mMediaPlayer.start();

                    mMediaPlayer.setOnCompletionListener(player -> {
                        player.start();
                        player.setLooping(true);
                    });
                }
            });

            mMediaPlayer.prepareAsync();
            Log.d(TAG, "createMediaPlayer: end");
        }
    }

    public void releaseMediaPlayer() {
        if (mMediaPlayer != null) {
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
    }

    @Override
    public void onPrepared(MediaPlayer mediaPlayer) {
        if (mediaPlayer != null) {
            mediaPlayer.start();
            Log.d(TAG, "onPrepared: start()");
        }
    }
}
